package com.pingtai.xinlang.login.login;

import java.io.BufferedInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.cookie.*;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.lexer.Source;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.json.JSONException;
import org.json.JSONObject;

import com.pingtai.ajax.entity.IndentTarget_163;
import com.pingtai.util.ChangeCharset;
import com.pingtai.util.DummyRedirectHandler;
import com.pingtai.util.HttpClientUtils;
import com.pingtai.util.Utils;
import com.pingtai.xinlang.login.dao.XinlangDao;
import com.pingtai.xinlang.login.entity.LoginUser;
import com.pingtai.xinlang.login.entity.XinlangLoginCookie;
import com.pingtai.xinlang.login.model.PreLoginInfo;
import com.pingtai.xinlang.login.util.BigIntegerRSA;
import com.pingtai.xinlang.login.util.FileUtil;

/**
 * 返回一个httpclient 里面有登录需要的session
 * 
 * @author hoot
 * 
 */
public class WeiboLoginService {
	
	private XinlangDao xinlangDao;
	private FeedUtils feedUtiles;
	

	public FeedUtils getFeedUtiles() {
		return feedUtiles;
	}

	public void setFeedUtiles(FeedUtils feedUtiles) {
		this.feedUtiles = feedUtiles;
	}

	public XinlangDao getXinlangDao() {
		return xinlangDao;
	}

	public void setXinlangDao(XinlangDao xinlangDao) {
		this.xinlangDao = xinlangDao;
	}

	public static String SINA_PK = "EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D24"
			+ "5A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD39"
			+ "93CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE"
			+ "1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443";
	

	private static final Log logger = LogFactory.getLog(WeiboLoginService.class);

	public boolean hasCookie(LoginUser loginUser){
		Date d = loginUser.getLastLoginDate();
		if(d!=null){
			return true;
		}
		return false;
	}
	
	public boolean isGuoqiOfCookie(LoginUser loginUser){
		Date d = loginUser.getLastLoginDate();
		Date now = new Date();
		if(d==null) return true;
		if((now.getTime()-d.getTime())>3*60*60*1000){
			return false;
		}
		return false;
	}
	
	public LoginUser getLoginUser(String name){
		return xinlangDao.getLoginUserByName(name);
	}
	
	public LoginUser getLastUseLoginUser(Integer id){
		return xinlangDao.getLastUseLoginUser(id);
	}
	
	
	
	public List<XinlangLoginCookie> getLoginCookie(LoginUser user){
		return xinlangDao.getLoginCookiesByUser(user);
	}
	
	public HttpClient setCookiesToClient(HttpClient client,List<XinlangLoginCookie> cookies){
		CookieStore cookieStore = new BasicCookieStore();
		for(int i=0;i<cookies.size();i++){
			XinlangLoginCookie xinlangLoginCookie = cookies.get(i);
			BasicClientCookie cookie = new BasicClientCookie("name", xinlangLoginCookie.getName());
			cookie.setValue(xinlangLoginCookie.getValue());
			cookie.setDomain(xinlangLoginCookie.getDomain());
			cookie.setExpiryDate(xinlangLoginCookie.getExpiry());
			cookie.setPath(xinlangLoginCookie.getValue());
			cookie.setVersion(xinlangLoginCookie.getVersion());
			cookieStore.addCookie(cookie);
		}
		((DefaultHttpClient)client).setCookieStore(cookieStore);
		return client;
	}
	
	public String getConent(String url,HttpClient client,String characet){
		return feedUtiles.getHomeWeiboConent(client, url,characet);
	}
	
	public IndentTarget_163 getIndentTargetInfo_xl(String content) throws UnsupportedEncodingException, ParserException{
		content = ChangeCharset.toUTF_8(content);
		Parser parser = Parser.createParser(content, "utf-8");
		NodeFilter nameFilter = new TagNameFilter("title");
		String name = "";
		NodeList nodes = parser.extractAllNodesThatMatch(nameFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				Node textnode = (Node) nodes.elementAt(i);
				name = textnode.toPlainTextString();
				name = Utils.NoString(name);
			}
		}
		return null;
	}
	
	public IndentTarget_163 getRenrenGzRenqiTarget(String url) throws Exception{
		LoginUser loginUser = getLastUseLoginUser(2);
		HttpClient client = HttpClientUtils.getHttpClient();
		client = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(url);  
		getMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");  
        getMethod.setHeader("Accept-Language","zh-cn");  
        getMethod.setHeader("Connection","Keep-Alive");  
        getMethod.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1 QIHU 360SE");  
        getMethod.setHeader("Host","page.renren.com");  
        getMethod.setHeader("Cookie",loginUser.getCookies());  
        HttpResponse response = client.execute(getMethod);
        InputStream in = response.getEntity().getContent();
        BufferedInputStream bin = new BufferedInputStream(in);
        String msg = Utils.InputStreamTOString(in, "utf-8");
		msg = Utils.unicodeToString(msg);
		IndentTarget_163 indentTarget_163 = parseRenrenGzRenqiHtml(msg);
		if(in!=null) in.close();
		return indentTarget_163;
	}
	
	public IndentTarget_163 getRenrenRenqiTarget(String url) throws Exception{
		LoginUser loginUser = getLastUseLoginUser(2);
		HttpClient client = null;
		client = HttpClientUtils.getHttpClient();
		client.getParams().setParameter("http.protocol.cookie-policy",
				CookiePolicy.BROWSER_COMPATIBILITY);
		client.getParams().setParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
		HttpGet getMethod = new HttpGet(url);  
		getMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");  
        getMethod.setHeader("Accept-Language","zh-cn");  
        getMethod.setHeader("Connection","Keep-Alive");  
        getMethod.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1 QIHU 360SE");  
        getMethod.setHeader("Host","www.renren.com");  
        getMethod.setHeader("Cookie",loginUser.getCookies());  
        HttpResponse response = client.execute(getMethod);
        InputStream in = response.getEntity().getContent();
        BufferedInputStream bin = new BufferedInputStream(in);
        String msg = Utils.InputStreamTOString(in, "utf-8");
		msg = Utils.unicodeToString(msg);
		IndentTarget_163 indentTarget_163 = new IndentTarget_163();
		indentTarget_163 = parseRenrenRenqiHtml(msg);
		if(in!=null) in.close();
		return indentTarget_163;
	}
	
	public IndentTarget_163 getIndentTarget_163_zb(String url) throws Exception{
		LoginUser loginUser = getLastUseLoginUser(1);
		
		Date lastLogin = loginUser.getLastLoginDate();
		Date now = new Date();
		HttpClient client = null;
		IndentTarget_163 indentTarget_163 = new IndentTarget_163();
		client = HttpClientUtils.getHttpClient();
//		if((now.getTime()-lastLogin.getTime())>=12*60*60*1000){
//			client = getLoginStatus(loginUser.getName(), loginUser.getPass());
//		}
		
		HttpGet getMethod = new HttpGet(url);  
          
        getMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");  
        //下面一行需要注释掉，不然返回数据是gzip压缩后的乱码  
        //getMethod.setRequestHeader("Accept-Encoding","gzip, deflate");  
        getMethod.setHeader("Accept-Language","zh-cn");  
        getMethod.setHeader("Connection","Keep-Alive");  
        getMethod.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1 QIHU 360SE");
        
        if(url.indexOf("e.weibo.com")!=-1){
        	getMethod.setHeader("Host","e.weibo.com"); 
        }else{
        	getMethod.setHeader("Host","weibo.com"); 
        }
        
        getMethod.setHeader("Cookie",loginUser.getCookies()); 
        HttpResponse response = client.execute(getMethod);
        InputStream in = response.getEntity().getContent();
        BufferedInputStream bin = new BufferedInputStream(in);
        String msg = Utils.InputStreamTOString(in, "utf-8");
//			client = getLoginStatus(loginUser.getName(), loginUser.getPass());
//			String msg = getConent(url, client);
			//解析
			msg = Utils.unicodeToString(msg);
			if(msg.indexOf("<script>STK && STK.pageletM && STK.pageletM.view({\"pid\":\"pl_content_weiboDetail")!=-1){
				msg = msg.substring(msg.indexOf("<script>STK && STK.pageletM && STK.pageletM.view({\"pid\":\"pl_content_weiboDetail"),
						msg.indexOf("<script>STK && STK.pageletM && STK.pageletM.view({\"pid\":\"pl_content_Base"));
				msg = msg.replace("<script>STK && STK.pageletM && STK.pageletM.view(", "");
				msg = msg.replace(")</script>", "");
				Map map = Utils.getMapFromJson(msg);
				String html = (String) map.get("html");
				indentTarget_163 = parseXlZfHtml(html);
			}
			
			if(msg.indexOf("<script>FM.view({\"ns\":\"pl.content.weiboDetail.index")!=-1){
				if(msg.indexOf("<script>FM.view({\"ns\":\"pl.third.recommend.index")!=-1){
					if(msg.indexOf("<script>FM.view({\"ns\":\"pl.third.recommend.index")<msg.indexOf("<script>FM.view({\"ns\":\"pl.content.weiboDetail.index")){
						msg = msg.substring(msg.indexOf("<script>FM.view({\"ns\":\"pl.content.weiboDetail.index"), msg.indexOf("</html>"));
					}else{
						msg = msg.substring(msg.indexOf("<script>FM.view({\"ns\":\"pl.content.weiboDetail.index"), msg.indexOf("<script>FM.view({\"ns\":\"pl.third.recommend.index"));
					}
					
				}else if(msg.indexOf("<script>FM.view({\"ns\":\"\",\"domid\":\"Pl_Core_RightTextSingle")!=-1){
					if(msg.indexOf("<script>FM.view({\"ns\":\"\",\"domid\":\"Pl_Core_RightTextSingle")<msg.indexOf("<script>FM.view({\"ns\":\"pl.content.weiboDetail.index")){
						msg = msg.substring(msg.indexOf("<script>FM.view({\"ns\":\"pl.content.weiboDetail.index"), msg.indexOf("</html>"));
					}else{
						msg = msg.substring(msg.indexOf("<script>FM.view({\"ns\":\"pl.content.weiboDetail.index"), msg.indexOf("<script>FM.view({\"ns\":\"\",\"domid\":\"Pl_Core_RightTextSingle"));
					}
				}
				msg = msg.replace("<script>FM.view(", "");
				msg = msg.replace(")</script>", "");
				Map map = Utils.getMapFromJson(msg);
				String html = (String) map.get("html");
				indentTarget_163 = parseXlZfHtml(html);
			}
			if(in!=null) in.close();
			return indentTarget_163;
	}
	
	public IndentTarget_163 getIndentTarget_163_fan(String url) throws Exception{
		LoginUser loginUser = getLastUseLoginUser(1);
		HttpClient client = null;
		IndentTarget_163 indentTarget_163 = new IndentTarget_163();
		//未登录client
		client = HttpClientUtils.getHttpClient();
		String noLoginMsg = getConent(url, client,"utf-8");
		InputStream in = null;
		if(noLoginMsg==null){
			noLoginMsg="";
		}
		noLoginMsg = Utils.unicodeToString(noLoginMsg);
		if(noLoginMsg.indexOf("FM.view({\"ns\":\"pl.header.head.index")!=-1){
			String name = parseXlFanNameHtml(noLoginMsg);
			noLoginMsg = noLoginMsg.substring(noLoginMsg.indexOf("<script>FM.view({\"ns\":\"pl.header.head.index"),
					noLoginMsg.indexOf("<script>FM.view({\"ns\":\"pl.nav.index"));
			noLoginMsg = noLoginMsg.replace("<script>FM.view(", "");
			noLoginMsg = noLoginMsg.replace(")</script>", "");
			Map map = Utils.getMapFromJson(noLoginMsg);
			String html = (String) map.get("html");
			indentTarget_163 = parseXlFanHtml(html);
			indentTarget_163.setName(name);
		}else if(noLoginMsg.indexOf("STK && STK.pageletM && STK.pageletM.view({\"pid\":\"pl_content_litePersonInfo")!=-1){
			String name = parseXlFanNameHtml(noLoginMsg);
			
			noLoginMsg = noLoginMsg.substring(noLoginMsg.indexOf("STK && STK.pageletM && STK.pageletM.view({\"pid\":\"pl_content_litePersonInfo"),
					noLoginMsg.indexOf("<script>STK && STK.pageletM && STK.pageletM.view({\"pid\":\"pl_common_relations"));
			noLoginMsg = noLoginMsg.replace("STK && STK.pageletM && STK.pageletM.view(", "");
			noLoginMsg = noLoginMsg.replace(")</script>", "");
			Map map = Utils.getMapFromJson(noLoginMsg);
			String html = (String) map.get("html");
			indentTarget_163 = parseXlFanNumHtml(html);
			indentTarget_163.setName(name);
		}else{
			client = HttpClientUtils.getHttpClient();
			HttpGet getMethod = new HttpGet(url);  
	          
	        getMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");  
	        //下面一行需要注释掉，不然返回数据是gzip压缩后的乱码  
	        //getMethod.setRequestHeader("Accept-Encoding","gzip, deflate");  
	        getMethod.setHeader("Accept-Language","zh-cn");  
	        getMethod.setHeader("Connection","Keep-Alive");  
	        getMethod.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1 QIHU 360SE");  
	        getMethod.setHeader("Host","weibo.com");  
	        getMethod.setHeader("Cookie",loginUser.getCookies()); 
	        HttpResponse response = client.execute(getMethod);
	        in = response.getEntity().getContent();
	        BufferedInputStream bin = new BufferedInputStream(in);
	        String msg = Utils.InputStreamTOString(in, "utf-8");
//			client = getLoginStatus(loginUser.getName(), loginUser.getPass());
//			String msg = getConent(url, client);
			//解析
			msg = Utils.unicodeToString(msg);
			if(msg.indexOf("<script>FM.view({\"ns\":\"pl.header.head.index")!=-1){
				msg = msg.substring(msg.indexOf("<script>FM.view({\"ns\":\"pl.header.head.index"),
						msg.indexOf("<script>FM.view({\"ns\":\"pl.nav.index"));
				msg = msg.replace("<script>FM.view(", "");
				msg = msg.replace(")</script>", "");
				Map map = Utils.getMapFromJson(msg);
				String html = (String) map.get("html");
				indentTarget_163 = parseXlFanHtml(html);
			}
		}
		if(in!=null) in.close();
			return indentTarget_163;
	}
	
	public HttpClient getNoLoginClient(){
		DefaultHttpClient client = (DefaultHttpClient) HttpClientUtils.getHttpClient();
		client.getParams().setParameter("http.protocol.cookie-policy",
				CookiePolicy.BROWSER_COMPATIBILITY);
		client.getParams().setParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
		return client;
	}
	
	public HttpClient getLoginStatus(String userName, String passWord) {
		DefaultHttpClient client = (DefaultHttpClient) HttpClientUtils
				.getHttpClient();

		CookieSpecFactory csf = new CookieSpecFactory() {
			public CookieSpec newInstance(HttpParams params) {
				return new BrowserCompatSpec() {
					@Override
					public void validate(Cookie cookie, CookieOrigin origin)
							throws MalformedCookieException {
						// Oh, I am easy
					}
				};
			}
		};

//		client.getCookieSpecs().register("easy", csf);
//		client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "easy");

		client.getParams().setParameter("http.protocol.cookie-policy",
				CookiePolicy.BROWSER_COMPATIBILITY);
		client.getParams().setParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 5000);

		HttpPost post = new HttpPost(
				"http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.11)");

		post.setHeader("Host","login.sina.com.cn");
		post.setHeader("Connection","keep-alive");
		
		PreLoginInfo info = null;
		try {
			info = getPreLoginBean(client);
		} catch (HttpException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		} catch (JSONException e) {
			logger.error(e);
		}

		long servertime = info.servertime;
		String nonce = info.nonce;
		String pwdString = servertime + "\t" + nonce + "\n" + passWord;
		String sp = new BigIntegerRSA().rsaCrypt(SINA_PK, "10001", pwdString);

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("entry", "weibo"));
		nvps.add(new BasicNameValuePair("gateway", "1"));
		nvps.add(new BasicNameValuePair("from", ""));
		nvps.add(new BasicNameValuePair("savestate", "7"));
		nvps.add(new BasicNameValuePair("useticket", "1"));
		nvps.add(new BasicNameValuePair("ssosimplelogin", "1"));
		nvps.add(new BasicNameValuePair("vsnf", "1"));
		// new NameValuePair("vsnval", ""),
		nvps.add(new BasicNameValuePair("su", encodeUserName(userName)));
		nvps.add(new BasicNameValuePair("service", "miniblog"));
		nvps.add(new BasicNameValuePair("servertime", servertime + ""));
		nvps.add(new BasicNameValuePair("nonce", nonce));
		nvps.add(new BasicNameValuePair("pwencode", "rsa2"));
		nvps.add(new BasicNameValuePair("rsakv", info.rsakv));
		nvps.add(new BasicNameValuePair("sp", sp));
		nvps.add(new BasicNameValuePair("encoding", "UTF-8"));
		nvps.add(new BasicNameValuePair("prelt", "48"));
		nvps.add(new BasicNameValuePair("returntype", "META"));
		nvps.add(new BasicNameValuePair(
				"url",
				"http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"));

		try {
			post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			
			String entity = EntityUtils.toString(response.getEntity());
			String url = entity.substring(
					entity.indexOf("http://weibo.com/ajaxlogin.php?"),
					entity.indexOf("code=0") + 6);
			// 获取到实际url进行连接
			
			
			HttpGet getMethod = new HttpGet(url);
			getMethod.setHeader("Host","weibo.com");
			getMethod.setHeader("Connection","keep-alive");
			response = client.execute(getMethod);
			getMethod = new HttpGet("http://weibo.com/u/3945635581/home?wvr=5&lf=reg");
			getMethod.setHeader("Host","weibo.com");
			getMethod.setHeader("Connection","keep-alive");
			getMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");  
	        getMethod.setHeader("Accept-Language","zh-cn");  
	        getMethod.setHeader("Connection","Keep-Alive");  
	        getMethod.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1 QIHU 360SE");  
			response = client.execute(getMethod);
			entity = EntityUtils.toString(response.getEntity());
		} catch (ParseException e) {
			logger.error(e);
		} catch (ClientProtocolException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
		// 保存cookies
		List<Cookie> cookies = client.getCookieStore().getCookies();
		// 判断是否保存过cookie
//		LoginUser loginUser = xinlangDao.getLoginUserByName(userName);
//		loginUser.setLastLoginDate(new Date());

		String s = "";
		boolean sue = false;
		boolean sup = false;
		for (int i = 0; i < cookies.size(); i++) {
			Cookie cookie = cookies.get(i);
			String name = cookie.getName();
			if(name.equalsIgnoreCase("sue")&&!sue){
				s += name + "="+cookie.getValue()+";";
				sue = true;
			}else if(name.equalsIgnoreCase("sup")&&!sup){
				s += name + "="+cookie.getValue()+";";
				sup = true;
			}
		}
//		loginUser.setCookies(s);
//		xinlangDao.update(loginUser);

		return client;
	}

	private  PreLoginInfo getPreLoginBean(HttpClient client)
			throws HttpException, IOException, JSONException {

		String serverTime = getPreLoginInfo(client);
		JSONObject jsonInfo = new JSONObject(serverTime);
		PreLoginInfo info = new PreLoginInfo();
		info.nonce = jsonInfo.getString("nonce");
		info.pcid = jsonInfo.getString("pcid");
		info.pubkey = jsonInfo.getString("pubkey");
		info.retcode = jsonInfo.getInt("retcode");
		info.rsakv = jsonInfo.getString("rsakv");
		info.servertime = jsonInfo.getLong("servertime");
		return info;
	}

	public  String getPreLoginInfo(HttpClient client)
			throws ParseException, IOException {
		String preloginurl = "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&"
				+ "callback=sinaSSOController.preloginCallBack&su="
				+ ""
				+ "&rsakt=mod&client=ssologin.js(v1.4.11)"
				+ "&_=" + getCurrentTime();
		HttpGet get = new HttpGet(preloginurl);

		HttpResponse response = client.execute(get);

		String getResp = EntityUtils.toString(response.getEntity());
		int firstLeftBracket = getResp.indexOf("(");
		int lastRightBracket = getResp.lastIndexOf(")");

		String jsonBody = getResp.substring(firstLeftBracket + 1,
				lastRightBracket);
		return jsonBody;

	}

	private  String getCurrentTime() {
		long servertime = new Date().getTime() / 1000;
		return String.valueOf(servertime);
	}

	private  String encodeUserName(String email) {
		email = email.replaceFirst("@", "%40");// MzM3MjQwNTUyJTQwcXEuY29t
		email = Base64.encodeBase64String(email.getBytes());
		return email;
	}
	
	public IndentTarget_163 parseRenrenGzRenqiHtml(String html) throws ParserException{
		Parser parser = Parser.createParser(html, "utf-8");
		NodeFilter nameFilter = new TagNameFilter("title");
		String name = "";
		NodeList nodes = parser.extractAllNodesThatMatch(nameFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  name=textnode.toHtml();
				  name = Utils.NoString(name);
				  if(name.indexOf("-公共主页")!=-1){
					  name=name.substring(0, name.indexOf("-公共主页")) ;
				  }else if(name.indexOf("的公共主页")!=-1){
					  name=name.substring(0, name.indexOf("的公共主页")) ;
				  }
				  
	              break;
			}
		}
		
		Parser parser2 = Parser.createParser(html, "utf-8");
		NodeFilter numFilter = new HasAttributeFilter("class", "num-green");
		String num = "";
		nodes = parser2.extractAllNodesThatMatch(numFilter);
		if (nodes != null&&nodes.size()>0) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  num=textnode.toPlainTextString();
				  num = Utils.NoString(num);
	              break;
			}
		}else{
			Parser parser3 = Parser.createParser(html, "utf-8");
			numFilter = new TagNameFilter("h4");
			nodes = parser3.extractAllNodesThatMatch(numFilter);
			if (nodes != null&&nodes.size()>0) {
				for (int i = 0; i < nodes.size(); i++) {
					  Node textnode = (Node) nodes.elementAt(i);
					  num=textnode.toPlainTextString();
					  num = Utils.NoString(num);
					  if(num.equals("关注者")){
						  Node n = textnode.getNextSibling().getNextSibling();
						  num = n.toPlainTextString();
						  num = num.replace("(", "");
						  num = num.replace(")", "");
						  break;
					  }
				}
			}
		}
		IndentTarget_163 target = new IndentTarget_163();
		target.setName(name);
		target.setNumber(num);
		return target;
	}
	
	public IndentTarget_163 parseRenrenRenqiHtml(String html) throws ParserException, UnsupportedEncodingException{
		Parser parser = Parser.createParser(html, "utf-8");
		NodeFilter nameFilter = new TagNameFilter("title");
		String name = "";
		NodeList nodes = parser.extractAllNodesThatMatch(nameFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  name=textnode.toHtml();
				  name = Utils.NoString(name);
				  name=name.replace("人人网 - ", "");
	              break;
			}
		}
		
		Parser parser2 = Parser.createParser(html, "utf-8");
		NodeFilter numFilter = new AndFilter(new TagNameFilter("span"),new HasAttributeFilter("class", "count"));
		String num = "";
		nodes = parser2.extractAllNodesThatMatch(numFilter);
		
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  num=textnode.toHtml();
				  num = Utils.NoString(num);
				  num = num.replace("(有", "");
				  num = num.replace("人看过)", "");
	              break;
			}
		}
		if(nodes==null||nodes.size()==0){
			parser2 = Parser.createParser(html, "utf-8");
			numFilter = new HasAttributeFilter("class", "avatar_title");
			num = "";
			nodes = parser2.extractAllNodesThatMatch(numFilter);
			if (nodes != null) {
				for (int i = 0; i < nodes.size(); i++) {
					  Node textnode = (Node) nodes.elementAt(i);
					  num=textnode.getFirstChild().getNextSibling().getFirstChild().toHtml();
					  num = Utils.NoString(num);
					  num = num.replace("(", "");
					  num = num.replace("人看过)", "");
					  num = num.replace("\t", "");
					  num = num.replace("\n", "");
		              break;
				}
			}
		}
		IndentTarget_163 target = new IndentTarget_163();
		target.setName(name);
		target.setNumber(num);
		return target;
	}
	
	public IndentTarget_163 parseXlZfHtml(String html) throws ParserException{
		Parser parser = Parser.createParser(html, "gbk");
		NodeFilter msgFilter = new HasAttributeFilter("node-type","feed_list_content");
		String msg = "";
		NodeList nodes = parser.extractAllNodesThatMatch(msgFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
	              msg=textnode.toHtml();
	              msg = Utils.NoString(msg);
	              msg = msg.replace(" ", "");
	              msg = msg.replace("\n", "");
	              break;
			}
		}
		Parser parser2 = Parser.createParser(html, "gbk");
		NodeFilter numFilter = new HasAttributeFilter("node-type","forward_counter");
		String num = "";
		nodes = parser2.extractAllNodesThatMatch(numFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  num=textnode.toHtml();
				  num = Utils.NoString(num);
				  if(num.indexOf("转发")!=-1){
					  if(num.length()==2){
						  num = "0";
						  break;
					  }
					  num = num.replace("转发(", "");
					  num = num.replace(")", "");
					  break;
				  }
			}
		}
		IndentTarget_163 indentTarget_163 = new IndentTarget_163();
		indentTarget_163.setMsg(msg);
		indentTarget_163.setNumber(num);
		return indentTarget_163;
	}
	
	public String parseXlFanNameHtml(String html) throws ParserException, UnsupportedEncodingException{
		Parser parser = Parser.createParser(html, "utf-8");
		html = ChangeCharset.changeCharset(html, ChangeCharset.GBK,ChangeCharset.UTF_8);
		NodeFilter nameFilter = new TagNameFilter("title");
		String name = "";
		NodeList nodes = parser.extractAllNodesThatMatch(nameFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  name=textnode.toHtml();
				  name = Utils.NoString(name);
				  name = ChangeCharset.changeCharset(name, ChangeCharset.GBK);
				  name = name.substring(0, name.indexOf("的微博"));
	              break;
			}
		}
		return name;
	}
	
	public IndentTarget_163 parseXlFanNumHtml(String html) throws ParserException{
		Parser parser = Parser.createParser(html, "gbk");
		NodeFilter numFilter = new HasAttributeFilter("class","user_atten clearfix");
		String num = "";
		NodeList nodes = parser.extractAllNodesThatMatch(numFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  num =  textnode.getChildren().elementAt(7).getFirstChild().getNextSibling().toHtml();
	              break;
			}
		}
		IndentTarget_163 t = new IndentTarget_163();
		t.setNumber(num);
		return t;
	}
	
	public IndentTarget_163 parseXlFanHtml(String html) throws ParserException{
		Parser parser = Parser.createParser(html, "utf-8");
		NodeFilter nameFilter = new HasAttributeFilter("class","name");
		String name = "";
		NodeList nodes = parser.extractAllNodesThatMatch(nameFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  name=textnode.toHtml();
				  name = Utils.NoString(name);
				  name = name.replace(" ", "");
				  name = name.replace("\n", "");
	              break;
			}
		}
		
		Parser parser2 = Parser.createParser(html, "gbk");
		NodeFilter numFilter = new HasAttributeFilter("node-type","fans");
		String num = "";
		nodes = parser2.extractAllNodesThatMatch(numFilter);
		if (nodes != null) {
			for (int i = 0; i < nodes.size(); i++) {
				  Node textnode = (Node) nodes.elementAt(i);
				  num=textnode.getNextSibling().toHtml();
				  num = Utils.NoString(num);
				
			}
		}
		
		  
		boolean isNum = num.matches("[0-9]+"); 
		IndentTarget_163 indentTarget_163 = new IndentTarget_163();
		if(!isNum){
			Parser parser3 = Parser.createParser(html, "gbk");
			numFilter = new HasAttributeFilter("class","W_tc");
			num = "";
			nodes = parser3.extractAllNodesThatMatch(numFilter);
			if (nodes != null) {
				for (int i = 0; i < nodes.size(); i++) {
					  Node textnode = (Node) nodes.elementAt(i);
					  num=textnode.toPlainTextString();
					  num = Utils.NoString(num);
					  num = num.substring(num.indexOf("关注")+2,num.indexOf("粉丝"));
					  Pattern p = Pattern.compile("\\s*|\t|\r|\n");
					  Matcher m = p.matcher(num);
					  num = m.replaceAll("");

					  indentTarget_163.setNumber(num);
					
				}
			}
		}else{
			indentTarget_163.setName(name);
			indentTarget_163.setNumber(num);
		}
		
		
		
		return indentTarget_163;
	}

}


